from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from consul import Consul, Check
import logging
from config import settings
from middleware.exception_handler import global_exception_handler
from api.http.controller.student_controller import router as student_router

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

app = FastAPI()

# 配置 CORS 中间件，允许所有来源的请求
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 注册学生路由
app.include_router(student_router, prefix="/api/v1", tags=["students"])

# 注册全局异常捕获中间件
app.add_exception_handler(Exception, global_exception_handler)


# 定义一个函数，用于将服务注册到 Consul 注册中心
def register_service():
    try:
        consul = Consul(settings.consul_host, settings.consul_port)
        # 调用 Consul 客户端的方法，注册当前服务
        consul.agent.service.register(
            name="fastapi-service",
            service_id="fastapi-service-1",
            address="localhost",
            port=8000,
            check=Check.http("http://localhost:8000/health", "10s"),  # 健康检查
        )
        logger.info("Service registered to Consul")
    except Exception as e:
        logger.error(f"Failed to register service: {e}")


# 定义一个函数，用于从 Consul 注册中心注销服务
def deregister_service():
    try:
        consul = Consul(settings.consul_host, settings.consul_port)
        consul.agent.service.deregister("fastapi-service-1")
        logger.info("Service deregistered from Consul")
    except Exception as e:
        logger.error(f"Failed to deregister service: {e}")


# 定义一个启动事件处理函数，在应用启动时注册服务
@app.on_event("startup")
def startup_event():
    register_service()


# 定义一个关闭事件处理函数，在应用关闭时注销服务
@app.on_event("shutdown")
def shutdown_event():
    deregister_service()


@app.get("/health")
def health():
    return {"status": "healthy"}


if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, host="0.0.0.0", port=8000)
